package cn.hairui.blog.controller;

import cn.hairui.blog.constant.PubConstant;
import cn.hairui.blog.model.User;
import cn.hairui.blog.model.WebInfo;
import cn.hairui.blog.model.Whisper;
import cn.hairui.blog.service.WebInfoService;
import cn.hairui.blog.service.WhisperService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @author lihairui
 * @version V1.0
 * @date: 2019/8/3 10:28
 */
@Controller
public class WhisperController {

    @Autowired
    private WebInfoService webInfoService;
    @Autowired
    private WhisperService whisperService;

    @RequestMapping(value = "whisper")
    public String whisper(HttpServletRequest request, Model model) {
        int pageSize = 20;//默认每页显示20条记录
        WebInfo webInfo = webInfoService.find(PubConstant.MY_INFO_ID);
        model.addAttribute("webinfo", webInfo);

        Integer pageNum = null;
        String pageNumStr = request.getParameter("pageIndex");
        if (pageNumStr != null) {
            pageNum = Integer.parseInt(pageNumStr);
        }
        if (pageNum == null) {
            pageNum = 1;
        }

        PageHelper.startPage(pageNum, pageSize);
        List<Whisper> whisperList = null;
        User userinfo = (User) request.getSession().getAttribute(PubConstant.GLOBAL_SESSION_NAME);
        if (userinfo != null && PubConstant.YES_NO_Y.equals(userinfo.getAdminflag())) {
            //管理用户（包括普通管理用户和超级管理用户） 可以查看所有
            whisperList = whisperService.list();
        } else {
            //普通用户或者游客 可以查看公开内容
            whisperList = whisperService.findGust();
        }


        List whispers = new ArrayList();
        Iterator iterator = whisperList.iterator();
        while (iterator.hasNext()) {
            Whisper whisper = (Whisper) iterator.next();
            //获取评论信息
            Map map = new HashMap();
            map.put("id", whisper.getId());
            map.put("content", whisper.getContent());
            map.put("createtime", whisper.getCreatetime());

            List<Map> whisperMessageList = whisperService.findMessageByWhisperId(whisper.getId());
            map.put("messages", whisperMessageList);
            map.put("mcount", whisperMessageList.size());
            whispers.add(map);
        }
        model.addAttribute("whispers", whispers);

        return "whisper";
    }
}
